package com.lxb.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxb.eduservice.entity.EduSubject;
import com.lxb.eduservice.entity.excel.SubjectData;
import com.lxb.eduservice.entity.subject.OneSubject;
import com.lxb.eduservice.entity.subject.TwoSubject;
import com.lxb.eduservice.listener.SubjectEasyExcelListener;
import com.lxb.eduservice.mapper.EduSubjectMapper;
import com.lxb.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author lixuebin
 * @since 2022-10-29
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            InputStream in = file.getInputStream();
            //处理数据在EasyExcelListener监听器部分
            EasyExcel.read(in, SubjectData.class, new SubjectEasyExcelListener(subjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //存放封装数据
        List<OneSubject> finalList = new ArrayList<>();

        //1.查询所有一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", "0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);

        //添加二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", "0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);


        //封装一级分类数据
        for (EduSubject one : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
//            oneSubject.setId(one.getId());
//            oneSubject.setTitle(one.getTitle());
            BeanUtils.copyProperties(one, oneSubject);//通过bean，把one的值复制到oneSubject(属性名需要相同)


            //封装二级分类
            List<TwoSubject> twoFinalSubjectList = new ArrayList<>();
            for (EduSubject two : twoSubjectList) {
                TwoSubject twoSubject = new TwoSubject();
                //判断一级id和二级父id
                if (one.getId().equals(two.getParentId())) {
                    BeanUtils.copyProperties(two, twoSubject);
                    twoFinalSubjectList.add(twoSubject);
                }
            }
            //在一级分类中存放二级分类信息
            oneSubject.setChildren(twoFinalSubjectList);
            //存放一级分类信息
            finalList.add(oneSubject);
        }
        return finalList;
    }
}
